const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken') // token 生成 及 验证
const { exec } = require('./db/index')

app.use(bodyParser()) // json form text

// token校验

// 登陆 /api/login
router.post('/api/login', async (ctx, next) => {
	// const { username, password } = ctx.query
	const { username, password } = ctx.request.body
	console.log('username:', username)
	if (username && password) {
		const data = await exec(
			`select * from users where username=? and password=?`,
			[username, password]
		)
		console.log('data:', data)
		// 生成token
		const token = jwt.sign(
			{
				id: data[0].id,
				username: data[0].username,
				info: data[0].info
			},
			'1904A',
			{
				expiresIn: '10min'
			}
		)
		ctx.body = {
			code: 0,
			msg: 'success',
			data: {
				token
			}
		}
	} else {
		ctx.body = { msg: '请输入账号密码' }
	}
})

// 过滤掉登陆和注册接口
const whiteList = ['/api/login', '/api/register']

// 定义了一个函数，用来识别用户身份
const asyncVerfiy = async (ctx, next) => {
	const { token } = ctx.request.headers
	console.log('token:', token)
	try {
		if (whiteList.indexOf(ctx.path) === -1) {
			// 找到了
			// 捕捉同步代码错误的
			const data = jwt.verify(token, '1904A')
			console.log('data:', data)
			// 将用户信息保存在state上，他就能传递到下一个中间件
			ctx.state.userInfo = data
		}
		await next()
	} catch (err) {
		ctx.body = { err }
	}
}

// 注册全局中间件 （用户验证用户身份的一个中间价）
app.use(asyncVerfiy)

router.get('/api/test', async (ctx, next) => {
	console.log('')
	ctx.body = { path: ctx.path }
})

router.post('/api/register', async (ctx, next) => {
	// const { username, password, address, gender = 1 } = ctx.query
	const { username, password, address, gender = 1 } = ctx.request.body
	// 1. 查询当前用户是否已经被注册
	const queryData = await exec(`select * from users where username=?`, [
		username
	])
	if (queryData.length === 0) {
		console.log('我在函数内部')
		// 2. 注册
		const data = await exec(
			`insert into users (username, password, address, gender) values (?, ?, ?, ?)`,
			[username, password, address, gender]
		)
		console.log('data:', data)
		if (data.affectedRows) {
			ctx.body = { data }
			return
		}
	}
	ctx.body = { msg: 'fail' }
})

// 查询用户 （分页 且 倒序）
router.get('/api/list', async (ctx, next) => {
	const { page = 1, size = 5 } = ctx.query
	console.log(ctx.state.userInfo, '----------------?')
	// size page 需要时number类型
	// const data = await exec(
	// 	`select * from users order by id desc limit ? offset ?`,
	// 	[size * 1, (page - 1) * size]
	// )
	const data = await exec(`select * from users where id=?`, [
		ctx.state.userInfo.id
	])
	ctx.body = {
		code: 0,
		msg: 'success',
		data
	}
})

// router.post('/api/list', async (ctx, next) => {}) // 添加

// 修改用户信息
router.put('/api/list/:id', async (ctx, next) => {
	const { id } = ctx.params
	const { username, password, address, gender, info } = ctx.request.body
	const data = await exec(`update users set info=? where id=?`, [info, id])
	ctx.body = { code: 0, msg: 'success', data }
})

router.delete('/api/list/:id', async (ctx, next) => {
	const { id } = ctx.params
	const data = await exec(`delete from users where id = ?`, [id])
	ctx.body = { code: 0, msg: 'success', data }
}) // 删除

// 注册路由级中间件
app.use(router.routes(), router.allowedMethods())

app.listen(3000, () => {
	console.log('http://localhost:3000')
})
